interface SpanObj {
  rowspan: number;
  colspan: number;
}

/**
 * 表格列合并
 * @param columnPropArr 表格顺序列
 * @param tableData 源数组
 * @param mergePropArr 源数组合并列
 * @param options 合并配置选项，顺序会限制合并优先级
 * @return 返回合并配置项
 */
export const buildObjectSpanArr = (
  columnPropArr: string[] = [],
  tableData: any[] = [],
  mergePropArr: string[] = []
): SpanObj[] => {
  const result: SpanObj[] = []; // 使用二维数组（此处将二维数组线性化）记录每行合并状态
  const resultColZero: number[] = []; // 记录每列合并时第一行序号

  tableData.forEach((_dataItem, rowIndex) => {
    const rowPos = rowIndex * columnPropArr.length;

    // 首行初始化
    if (rowIndex === 0) {
      columnPropArr.forEach((_column, col) => {
        result[rowPos + col] = {
          rowspan: 1,
          colspan: 1,
        };
        resultColZero[col] = rowIndex;
      });
    } else {
      for (let col = 0; col < columnPropArr.length; col++) {
        // 参与合并
        if (mergePropArr.includes(columnPropArr[col])) {
          // 如果当前单元格和前一行单元格相等
          if (tableData[rowIndex][columnPropArr[col]] === tableData[rowIndex - 1][columnPropArr[col]]) {
            // 合并优先级限制
            let canMerge = true
            for (let i=0; i<mergePropArr.length; i++) {
              if (mergePropArr[i] === columnPropArr[col]) {
                break
              }
              if (tableData[rowIndex][mergePropArr[i]] !== tableData[rowIndex - 1][mergePropArr[i]]) {
                canMerge = false
                break
              }
            }

            if (canMerge) {
              result[rowPos + col] = {
                rowspan: 0,
                colspan: 0,
              };
              const beforeItem = result[resultColZero[col] * columnPropArr.length + col];
              beforeItem.rowspan++;
              continue
            }
          }

        }

        // 未参与合并
        result[rowPos + col] = {
          rowspan: 1,
          colspan: 1,
        };
        resultColZero[col] = rowIndex;
      }
    }
  });

  return result;
};

/**
 * 表格列合并项获取
 * @param cellSpanArr 合并配置选项
 * @param columnPropArr 表格顺序列
 * @param rowPos 行序号
 * @param columnIndex 列序号
 */
export const getObjectSpan = (
  cellSpanArr: SpanObj[] = [],
  columnPropArr: any[] = [],
  rowPos: number,
  columnIndex: number
): SpanObj => {
  return cellSpanArr[rowPos * columnPropArr.length + columnIndex];
};

export const useTableSpanArr = () => {
  let cellSpanArr = []

  function buildCellSpanArrByCol(
    columnPropArr: string[] = [],
    tableData: any[] = [],
    mergePropArr: string[] = []
  ) {
    cellSpanArr = buildObjectSpanArr(columnPropArr, tableData, mergePropArr)
  }

  function getCellSpan(
    columnPropArr: any[] = [],
    rowPos: number,
    columnIndex: number
  ): SpanObj {
    return getObjectSpan(cellSpanArr, columnPropArr, rowPos, columnIndex)
  }

  return {
    cellSpanArr,
    getCellSpan,
    buildCellSpanArrByCol
  }
}
